home *** CD-ROM | disk | FTP | other *** search
- /*
- ** STACK.C - A Simple Stack routine
- **
- **
- ** This file contains the Push() and Pop() functions for implementing a
- ** Stack in 'C'. The stack is actually an array of integers, fixed in
- ** size which does not really follow the definition of a stack which is:
- ** A dynamically shrinking and growing LIFO data structure.
- **
- ** Several uses of the Stack in actual practice are implemented below such
- ** as local variable storage, parameter passing and recuresion. This
- ** file is for academic use only and is not intended as an efficient
- ** stack system for actual useage.
- **
- **
- ** To Compile: TCC or QCL STACK.C
- **
- ** Mario Giannini
- **
- */
- #define MAXSTACKSIZE 15 /* Keep the stack small so error arises and are seen */
-
- struct _STACK_ {
- int Pointer, Elements[MAXSTACKSIZE];
- } RealStack;
-
- main()
- {
- int n;
- RealStack.Pointer=0;
- do {
- printf("\n1 Add\n2 Get ");
- n=getch();
- if(n=='1')
- {
- printf("\nEnter an integer: ");
- scanf("%d", &n);
- Push(n);
- }
- else
- if(n=='2')
- {
- n=Pop();
- printf("\n\nValue is %d\n", n);
- }
- } while(n!=27);
-
- printf("\n\n");
- Push(3); /* Parameters to the AddEm function */
- Push(4);
- Push(5);
- Push(3);
- AddEm();
-
- printf("%d\n", Recursive());
-
- }
-
-
- Push(int n)
- {
- if(RealStack.Pointer==MAXSTACKSIZE)
- {
- printf("Stack overflow\n");
- return;
- }
- RealStack.Elements[RealStack.Pointer++]=n;
- }
-
- Pop()
- {
- int n;
- if(!RealStack.Pointer)
- {
- printf("Stack underflow\n");
- return(0);
- }
- n=RealStack.Elements[--RealStack.Pointer];
- return(n);
- }
-
- AddEm() /* An example of parameter passing via the Stack */
- {
- int i=0, j;
-
- j=Pop();
- while(j--)
- i+=Pop();
- printf("The total is %d\n", i);
- }
-
- Recursive() /* An example of recursion and local storage via the Stack */
- {
- Push(0);
-
- printf("Enter an integer (0 stops): ");
- scanf("%d", &RealStack.Elements[RealStack.Pointer-1]);
- if(RealStack.Elements[RealStack.Pointer-1]!=0)
- RealStack.Elements[RealStack.Pointer-1]+=Recursive();
- return(Pop());
- }